package orm.infrastructure.converters;

import orm.er.PhoneMock;
import orm.infrastructure.interfaces.IMockConverter;
import orm.infrastructure.interfaces.IValidable;

import java.util.Dictionary;
import java.util.Hashtable;

/**
 * Created with IntelliJ IDEA.
 * User: Awake
 * Date: 03.05.12
 * Time: 17:41
 * To change this template use File | Settings | File Templates.
 */
public class PhoneConverter implements IMockConverter {

    private static final String PHONE_ID_FIELD = "phoneID";
    private static final String PERSON_ID_FIELD = "personID";
    private static final String PHONE_FIELD = "phone";
    private static final int PHONE_FIELDS_COUNT = 3;

    @Override
    public Dictionary<String, Object> toDictionary(IValidable mock) {

        PhoneMock phoneMock = (PhoneMock) mock;
        if (phoneMock.isNullable())
            throw new NullPointerException();

        Dictionary<String, Object> dictionary = new Hashtable<String, Object>(PHONE_FIELDS_COUNT);
        dictionary.put(PHONE_ID_FIELD, phoneMock.getPhoneID());
        dictionary.put(PERSON_ID_FIELD, phoneMock.getPersonID());
        dictionary.put(PHONE_FIELD, phoneMock.getPhone());

        return dictionary;
    }

    @Override
    public IValidable toObject(Dictionary<String, Object> dictionary) {

        if (dictionary.isEmpty())
            throw new NullPointerException();

        PhoneMock phoneMock = new PhoneMock();

        if (dictionary.get(PHONE_ID_FIELD) != null) {
            phoneMock.setPhoneID((Integer) dictionary.get(PHONE_ID_FIELD));
        }
        if (dictionary.get(PERSON_ID_FIELD) != null) {
            phoneMock.setPersonID((Integer) dictionary.get(PERSON_ID_FIELD));
        }
        if (dictionary.get(PHONE_FIELD) != null) {
            phoneMock.setPhone((String) dictionary.get(PHONE_FIELD));
        }

        return phoneMock;
    }
}
